import { useRef, useEffect, useState } from 'react'
import { connect } from 'react-redux';
import { publish, subscribe, unsubscribe } from 'pubsub-js';
import { RTrim } from '../../assets/js/tools'

import {
    chat_input_input,
    chat_input_control,
    chat_input_send_btn,
} from './index.module.css'
import { postMessageToGroup } from '../../assets/js/api'
import { findEmoji } from '../../assets/js/emoji'
import { sendMessage, sendDone, sendFail } from '../../event-type';
import ChatHelper from '../chatHelper';

function ChatFooter(props) {

    const textMax = 255;    // 文本最大输入值

    const { user_id, group_id } = props;
    const [inputMessage, setInpuMessage] = useState('');
    const inputMessageDom = useRef();


    useEffect(() => {
        const insertMessafeToken = subscribe('insert_message', insertMessage);
        return () => {
            unsubscribe(insertMessafeToken);
        }
    }, []);
    useEffect(() => {
        inputMessageDom.current.value = findEmoji(inputMessage);
    }, [inputMessage])

    function judgeSendMessage() {
        const msg = RTrim(inputMessage);
        if (!msg || group_id === 0) {
            // 系统消息不发送
            setInpuMessage('');
            return;
        }
        // 消息loading
        const message_id = +`${new Date().getTime()}${user_id}`;
        publish(sendMessage, {msg, message_id});

        // 发送消息
        postMessageToGroup({user_id, group_id, msg})
        .then(res => {
            const { code } = res.data;
            if (code === 1) {
                // 发送成功,清除loading提示
                publish(sendDone, {message_id});
            } else {
                // 发送失败,出现红色感叹号,点击重新发送
                publish(sendFail, {message_id});
            }
            setInpuMessage('');
        })
        .catch(err => {
            console.log(err);
            publish(sendFail, {message_id});
        });
    }
    
    function insertMessage(eventName, str) {
        setInpuMessage(curStr => curStr + str);
    }


    return (
        <>
            <ChatHelper />
            <div>
                <textarea className={chat_input_input} type="text" ref={inputMessageDom}
                    onInput={(e) => {
                        if (e.target.value.length > textMax) {
                            e.target.value = e.target.value.slice(0, textMax);
                        }
                        setInpuMessage(e.target.value);
                    }} 
                    onKeyDown={(e) => {
                        if (e.shiftKey && e.key === 'Enter') {
                            e.preventDefault();
                            e.target.value = e.target.value + '\n';
                            return;
                        }
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            judgeSendMessage();
                        }
                    }}
                />
                <div className={chat_input_control}>
                    <button className={chat_input_send_btn} onClick={judgeSendMessage}>发送</button>
                </div>
            </div>
        </>
    )
}

function mapStateToProps(state) {
    return {
        user_id: state.user.id,
        group_id: state.currentRoom,
    }
}
export default connect(
    mapStateToProps,
    {

    }
)(ChatFooter);

